package org.scboy.common.request.inter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.parser.XmlTreeBuilder;
import org.scboy.utils.caches.dbms.entity.InterEntity;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;

import cn.hutool.core.io.IoUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 国际化提示语言
 * @author yanghao
 *
 */
@Configurable
public class InterScan {
	
	private static Log log=LogFactory.get();
	

	@Value("${spring.application.name}")
	String appName;
	
	/**
	 * 扫描配置信息
	 */
	public List<InterEntity> scanLang(){
		List<InterEntity> list=new ArrayList<InterEntity>();
		// 定义一个枚举的集合 并进行循环来处理这个目录下的things
		Enumeration<URL> dirs;
		try {
			//从classpath根开始扫描
			dirs = Thread.currentThread().getContextClassLoader().getResources("");
			// 循环迭代下去
			while (dirs.hasMoreElements()) {
				// 获取下一个元素
				URL url = dirs.nextElement();
				// 得到协议的名称
				String protocol = url.getProtocol();
				if ("file".equals(protocol)) {
					// 获取包的物理路径
					String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
					File file = new File(filePath);
					if(file.isDirectory()){
						//如果是文件夹
						list.addAll(scanDir(file));
					}else{
						//如果是文件
						list.addAll(fileConfig(file));
					}
				} else if ("jar".equals(protocol)) {
					JarFile jar = ((JarURLConnection) url.openConnection())
							.getJarFile();
					// 从此jar包 得到一个枚举类
					Enumeration<JarEntry> entries = jar.entries();
					while (entries.hasMoreElements()) {
						JarEntry entry = entries.nextElement();
						//如果是文件夹，继续下一个。
						if(entry.isDirectory()){
							continue;
						}
						list.addAll(jarConfig(jar, entry));
					}
				}
			}
		} catch (IOException e) {
			throw new RuntimeException("初始化异常，扫描国际语言文件出错。",e);
		}
		return list;
	}
	
	/**
	 * 循环读取文件夹
	 * @param dir
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	private List<InterEntity> scanDir(File dir) throws FileNotFoundException, IOException{
		List<InterEntity> list=new ArrayList<InterEntity>();
		File [] files=dir.listFiles();
		for (File file : files) {
			if(file.isFile()){
				list.addAll(fileConfig(file));
			}else{
				list.addAll(scanDir(file));
			}
		}
		return list;
	}
	
	/**
	 * 读取文件方式配置
	 * @param file
	 */
	@SuppressWarnings("resource")
	private List<InterEntity> fileConfig(File file) throws FileNotFoundException{
		String fname=file.getName();
		if (fname.toLowerCase(Locale.ENGLISH).endsWith(".inter.xml")) {
			log.info("扫描到国际化语言配置[XML]["+fname+"]配置,路径：["+file.getAbsolutePath()+"]");
			return readInter(fname.replace(".inter.xml", ""),new FileInputStream(file));
		}else {
			return new ArrayList<InterEntity>();
		}
	}
	/**
	 * 读取jar包中的文件读取
	 * @param jar
	 * @param entry
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private List<InterEntity> jarConfig(JarFile jar,JarEntry entry) throws IOException{
		String fname=entry.getName();
		if(fname.lastIndexOf("/")>-1){
			fname=fname.substring(fname.lastIndexOf("/")+1);
		}
		if (fname.toLowerCase(Locale.ENGLISH).endsWith(".inter.xml")) {
			log.info("扫描到国际化语言配置[XML]["+fname+"]配置,路径：["+jar.getName()+"!"+entry.getName()+"]");
			return readInter(fname.replace(".inter.xml", ""),jar.getInputStream(entry));
		}else {
			return new ArrayList<InterEntity>();
		}
	}
	
	/**
	 * 读取国际化语言配置
	 * @param language
	 * @param inputStream
	 * @throws IOException
	 */
	private List<InterEntity> readInter(String lang,InputStream inputStream){
		List<InterEntity> interList=new ArrayList<InterEntity>();
		//XML方式的配置文件
		Document doc;
		try {
			doc = Jsoup.parse(inputStream,"UTF-8","",new Parser(new XmlTreeBuilder()));
			for (Element el : doc.select("msg")) {
				String code=el.attr("code").replace("\\s", "");
				String name=el.attr("name").replace("\\s", "");
				String msg=el.text();
				//log.info("国际语言配置["+lang+"]：["+code+"]"+msg);
				
				InterEntity entity=new InterEntity();
				entity.setAppName(appName);
				entity.setCode(code);
				entity.setLang(lang);
				entity.setMsg(msg);
				entity.setName(name);
				interList.add(entity);
			}
		} catch (IOException e) {
		}finally {
			IoUtil.close(inputStream);
		}
		return interList;
	}
}
